package com.creditcmsplt.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.creditcmsplt.entity.CreditAuoth;
import com.creditcmsplt.entity.param.ApiTokenReq;
import com.creditcmsplt.entity.param.ApiTokenRsp;
import com.creditcmsplt.entity.param.ApiTokenRspData;
import com.creditcmsplt.service.CreditApiService;
import com.creditcmsplt.service.CreditAuothService;
import com.creditcmsplt.util.TextUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 征信资料上传获取用户token
 * @author leiyangjun
 *
 */
@RestController
@RequestMapping("api")
@Api(value = "api", tags = { "2.0,用于获取api token" },description="api")
public class ApiTokenController {
	
	private final Logger log = LoggerFactory.getLogger(ApiTokenController.class);
	
	@Autowired
	private CreditAuothService creditAuothService;
	
	@Autowired
	private CreditApiService creditApiService;
	
	/**
	 * 征信报告pdf转csv
	 * 
	 * @return
	 */
	@ApiOperation(value="获取开发平台接口访问授权码")
	@RequestMapping(value = "/getToken", method = RequestMethod.POST)
	public ApiTokenRsp applyCreditReport(@RequestBody ApiTokenReq tokenParam,HttpServletRequest req) {
		log.info(req.getServletPath());
		ApiTokenRsp tokenRspInfo=new ApiTokenRsp();
		ApiTokenRspData data=new ApiTokenRspData();
		Integer code=1;
		String msg="成功";
		String token="";
		creditApiService.insert("",tokenParam.getData().getVendor_key(),tokenParam.getData().getVendor_secret(),1,req.getServletPath());
		if(tokenParam==null||tokenParam.getData()==null
				||TextUtils.isEmpty(tokenParam.getData().getVendor_key())
				||TextUtils.isEmpty(tokenParam.getData().getVendor_secret())) {
			code=-1;
			msg="参数解析错误,无法解析请求参数.";
		}else {
			try {
				CreditAuoth creditAuoth=this.creditAuothService.queryToken(tokenParam.getData().getVendor_key(), tokenParam.getData().getVendor_secret());
				code=creditAuoth==null?-1:1;
				msg=creditAuoth==null?"没有该用户授权":"成功";
				token=creditAuoth==null?"":creditAuoth.getToken();
			} catch (Exception e) {
				log.error("",e);
				code=-1;
				msg="参数解析错误";
				token="";
			}
		}
		data.setCode(code);
		data.setMsg(msg);
		data.setToken(token);
		tokenRspInfo.setData(data);
		return tokenRspInfo;
	}
}
